package com.spider.admin.scaffold.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2025/3/18 10:19 下午
 */

@Lazy
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


  @Override
  public void insertFill(MetaObject metaObject) {
    Optional<Object> optional = Optional.ofNullable(SecurityContextHolder.getContext())
        .map(SecurityContext::getAuthentication)
        .map(Authentication::getPrincipal);
    if (optional.isPresent()) {
      Object principal = optional.get();
      if (!"anonymousUser".equals(principal)) {
        // 系统内的更新没有用户信息,此方法获取到的是anonymousUser（匿名用户的意思）
        this.setFieldValByName("createUser", principal, metaObject);
      }
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    Optional<Object> optional = Optional.ofNullable(SecurityContextHolder.getContext())
        .map(SecurityContext::getAuthentication)
        .map(Authentication::getPrincipal);
    if (optional.isPresent()) {
      Object principal = optional.get();
      if (!"anonymousUser".equals(principal)) {
        // 系统内的更新没有用户信息,此方法获取到的是anonymousUser（匿名用户的意思）
        this.setFieldValByName("updateUser", principal, metaObject);
      }
    }
  }
}
